package com.young.shop.api.controller;


import com.young.shop.pojo.vo.BaseRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传
 */
@Api(tags = "文件操作接口")
@Controller
public class FileController {

    @ApiOperation("文件上传")
    @PostMapping(value = "/upload", consumes = "multipart/*",
            headers = "content-type=multipart/form-data")
    @ResponseBody
    public BaseRespVO upload(@ApiParam(value = "文件") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件上传失败");
        }
        //获得文件地址
        String baseDir = "D:\\temp\\img";
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());
        String dir = baseDir + File.separator + dateStr;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            //创建目录
            dirFile.mkdirs();
        }

        String oldFileName = file.getOriginalFilename();
        String fileSuffix = oldFileName.substring(oldFileName.lastIndexOf(".")
                , oldFileName.length());
        String fileName = System.currentTimeMillis() + fileSuffix;
        String path = dir + File.separator + fileName;
        System.out.println("path:" + path);

        //存储路径：D:\temp\img\20201230\1609315210386.jpg
        //访问路径：http://ip:port/shop-img/20201230/1609315210386.jpg
        //动态资源路径：/20201230/1609315210386.jpg
        //http://ip:port/shop-img/



        try {
            //保存文件
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseRespVO();
    }
}
